package org.scalpel.mainApps.HHObjects;

import ioio.lib.api.DigitalOutput;
import ioio.lib.api.IOIO;
import ioio.lib.api.PwmOutput;
import ioio.lib.api.DigitalOutput.Spec.Mode;
import ioio.lib.api.exception.ConnectionLostException;

import org.scalpel.common.HHObject;

/**
 * 
 * @author Marcello R. de Oliveira
 * Control actuator by a PWM output from IOIO
 * Il faut choisir le pin et la frequence du PWM dans worldmap.xml
 */

public class Actuator extends HHObject {
	
	private float dutyCycle;
	private int pwmFreq;
	private boolean fIsSimulation = false;
	private int fPin = 0; 
	private IOIO fIoio;
	private PwmOutput fPwmOutput;
	//private DigitalOutput fDigitalOutput;
	
	
	public Actuator(String name, int pin, int pwmFreq, float dutyCycle){
		super(name);
		this.pwmFreq=pwmFreq;
		this.dutyCycle=dutyCycle;
		fPin=pin;
	}
	
	protected void finalize() throws Throwable
	{
		if( fPwmOutput != null)
			fPwmOutput.close();
	  super.finalize(); //not necessary if extending Object.
	}
	
	public void initIOIO(boolean isSimulation, IOIO ioio){
		fIsSimulation = isSimulation;

		if(fIsSimulation) return;
		
		fIoio = ioio;
		try {
			fPwmOutput = fIoio.openPwmOutput(new DigitalOutput.Spec(fPin, Mode.NORMAL), pwmFreq);
		} catch (ConnectionLostException e) {
			e.printStackTrace();
		};
		
		/*try {
			fPwmOutput = fIoio.openPwmOutput(fDigitalOutput);
		} catch (ConnectionLostException e) {
			e.printStackTrace();
		};*/
		
	}
	
	public void updateIOIO(){
			
			if( fIsSimulation ) return;
			//fDigitalOutput.
			
			try {
				fPwmOutput.setDutyCycle(dutyCycle);
			} catch (ConnectionLostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		
	}
}
